/**
 * Pagination Widget.
 * Dependencies: jQuery, jQuery-UI
 */

define(["jquery", "jquery-ui", "css!pagination-style"], function($) {
	$.widget("sopaths.pagination", {

		options: {
			currentPage: 1,
			totalPage: 1,
			leftEdge: 4,
			rightEdge: 4,
			pageChange: function(page) {}
		},

		paginationUl: null,

		_create: function() {
			this._generateElements();
		},

		_setOption: function() {
			this._generateElements();
		},

		_generateElements: function() {
			this.paginationUl = $("<ul class='sopaths-pagination-ul'></ul>");
			if (this.options.currentPage > 1) {
				this.paginationUl.append(this._generatePageElement("上一页", this.options.currentPage - 1));
			}
			var startIndex = this.options.currentPage - this.options.leftEdge < 1 ? 1 : this.options.currentPage - this.options.leftEdge;
			var endIndex = this.options.currentPage + this.options.rightEdge > this.options.totalPage ? this.options.totalPage : this.options.currentPage + this.options.rightEdge;
			if (startIndex > 1) {
				this.paginationUl.append(this._generatePageElement("1", 1));
			}
			if (startIndex > 2) {
				this.paginationUl.append($("<li>...</li>"));
			}

			for (var i = startIndex; i <= endIndex; i++) {
				var pageElement = this._generatePageElement(i, i);
				if (i == this.options.currentPage) {
					pageElement.addClass("sopaths-pagination-current");
				}
				this.paginationUl.append(pageElement);
			}

			if (endIndex < this.options.totalPage - 1) {
				this.paginationUl.append($("<li>...</li>"));
			}
			if (endIndex < this.options.totalPage) {
				this.paginationUl.append(this._generatePageElement(this.options.totalPage, this.options.totalPage));
			}
			if (this.options.currentPage < this.options.totalPage) {
				this.paginationUl.append(this._generatePageElement("下一页", this.options.currentPage + 1));
			}
			this.element.empty();
			this.element.append(this.paginationUl);
		},

		_generatePageElement: function(text, pageNum) {
			var a = $("<a>" + text + "</a>");
			a.on('click', $.proxy(function(event) {
				event.preventDefault();
				var innerPageNum = pageNum;
				if (innerPageNum != this.options.currentPage) {
					this.options.currentPage = innerPageNum;
					this._generateElements();
					this.options.pageChange(innerPageNum);
				} else {
					console.log("page number does not change.");
				}
			}, this));
			var li = $("<li></li>");
			li.append(a);
			return li;
		}
	});
});